package org.example.factory;

import org.example.annotation.Select;
import org.example.pojo.User;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: luyg
 * @Date: 2024/08/31/22:26
 * @Description:
 */
public class MapperProxyFactory {

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
    public static <T> T getMapper(Class<T> mapper){
        Object newProxyInstance = Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[]{mapper}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                Connection connection = DriverManager.getConnection("jdbc:mysql://192.168.56.103:3306/mydatabase?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8",
                        "root", "123456");

                Select annotation = method.getAnnotation(Select.class);
                String sqlValue = annotation.value();

                PreparedStatement select = connection.prepareStatement("select *from user where name =?");
                select.setString(1,"gangan");
                select.execute();
                List<User> list=new ArrayList<>();
                ResultSet resultSet = select.getResultSet();

                while (resultSet.next()){
                    User user = new User();
                    user.setId(resultSet.getInt("id"));
                    user.setName(resultSet.getString("name"));
                    list.add(user);
                }
                connection.close();
                return list;
            }
        });
        return (T) newProxyInstance;

    }
}
